package com.example.demo.test.lecture.httpstest;

import com.alibaba.csb.sdk.HttpCallerException;
import com.alibaba.csb.sdk.SdkLogger;
import com.example.demo.test.lecture.httpstest.ContentBody.Type;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidParameterException;
import java.util.*;
import java.util.Map.Entry;

public class HttpClientHelper {
    public HttpClientHelper() {
    }

    public static void printDebugInfo(String msg) {
        if (SdkLogger.isLoggable()) {
            SdkLogger.print(msg);
        }

    }

    public static void mergeParams(Map<String, List<String>> urlParamsMap, Map<String, String> paramsMap, boolean decodeFlag) throws HttpCallerException {
        if (paramsMap != null) {
            Iterator var4 = paramsMap.entrySet().iterator();

            while(var4.hasNext()) {
                Entry<String, String> kv = (Entry)var4.next();
                String value = decodeValue((String)kv.getKey(), (String)kv.getValue(), decodeFlag);
                urlParamsMap.put(kv.getKey(), Arrays.asList(value));
            }
        }

    }

    public static Map<String, String> newParamsMap(Map<String, List<String>> paramsMap, String apiName, String version, String accessKey, String securityKey, boolean timestampFlag, boolean nonceFlag, Map<String, String> extSignHeaders, StringBuffer signDiagnosticInfo, String signImpl, String verifySignImpl) {
        System.out.println(paramsMap==null);
        return SignUtil.newParamsMap(paramsMap, apiName, version, accessKey, securityKey, timestampFlag, nonceFlag, extSignHeaders, signDiagnosticInfo, signImpl, verifySignImpl);
    }

    public static String trimWhiteSpaces(String value) {
        return value == null ? value : value.trim();
    }

    public static String trimUrl(String requestURL) {
        int pos = requestURL.indexOf("?");
        String ret = requestURL;
        if (pos >= 0) {
            ret = requestURL.substring(0, pos);
        }

        return ret;
    }

    public static void validateParams(String apiName, String accessKey, String securityKey, Map<String, String> paramsMap) throws HttpCallerException {
        if (apiName == null) {
            throw new HttpCallerException(new InvalidParameterException("param apiName can not be null!"));
        } else if (accessKey != null && securityKey == null) {
            throw new HttpCallerException(new InvalidParameterException("param securityKey can not be null for a given accessKey!"));
        } else {
            if (paramsMap != null) {
                Iterator var4 = paramsMap.entrySet().iterator();

                while(var4.hasNext()) {
                    Entry<String, String> kv = (Entry)var4.next();
                    if (kv.getValue() == null) {
                        throw new HttpCallerException(new InvalidParameterException(String.format("bad parasMap, the value for key [ %s ] is null, please remove the key or set its value, e.g. \"\"!", kv.getKey())));
                    }
                }
            }

        }
    }

    private static String decodeValue(String key, String value, boolean decodeFlag) throws HttpCallerException {
        if (decodeFlag) {
            if (value == null) {
                throw new HttpCallerException("bad params, the value for key {" + key + "} is null!");
            } else {
                return URLDecoder.decode(value);
            }
        } else {
            return value;
        }
    }

    public static Map<String, List<String>> parseUrlParamsMap(String requestURL, boolean decodeFlag) throws HttpCallerException {
        boolean questionMarkFlag = requestURL.contains("?");
        Map<String, List<String>> urlParamsMap = new HashMap();
        if (questionMarkFlag) {
            int pos = requestURL.indexOf("?");
            String paramStr = requestURL.substring(pos + 1);
            String[] params = paramStr.split("&");
            String[] var9 = params;
            int var10 = params.length;

            for(int var11 = 0; var11 < var10; ++var11) {
                String param = var9[var11];
                pos = param.indexOf("=");
                if (pos <= 0) {
                    throw new HttpCallerException("bad request URL, url params error:" + requestURL);
                }

                String key = decodeValue("", param.substring(0, pos), decodeFlag);
                String value = param.substring(pos + 1);
                List<String> values = (List)urlParamsMap.get(key);
                if (values == null) {
                    values = new ArrayList();
                }

                ((List)values).add(decodeValue(key, value, decodeFlag));
                urlParamsMap.put(key, values);
            }
        }

        return urlParamsMap;
    }

    private static void setHeaders(HttpPost httpPost, Map<String, String> newParamsMap) {
        if (newParamsMap != null) {
            Iterator var2 = newParamsMap.entrySet().iterator();

            while(var2.hasNext()) {
                Entry<String, String> kv = (Entry)var2.next();
                httpPost.addHeader((String)kv.getKey(), (String)kv.getValue());
            }
        }

    }

    public static void setHeaders(HttpGet httpGet, Map<String, String> newParamsMap) {
        if (newParamsMap != null) {
            Iterator var2 = newParamsMap.entrySet().iterator();

            while(var2.hasNext()) {
                Entry<String, String> kv = (Entry)var2.next();
                httpGet.addHeader((String)kv.getKey(), (String)kv.getValue());
            }
        }

    }

    public static String genCurlHeaders(Map<String, String> newParamsMap) {
        if (newParamsMap == null) {
            return "";
        } else {
            StringBuffer sb = new StringBuffer();
            Iterator var2 = newParamsMap.entrySet().iterator();

            while(var2.hasNext()) {
                Entry<String, String> kv = (Entry)var2.next();
                sb.append("-H \"").append((String)kv.getKey()).append(":").append((String)kv.getValue()).append("\"  ");
            }

            return sb.toString();
        }
    }

    public static String createPostCurlString(String url, Map<String, String> params, Map<String, String> headerParams, ContentBody cb, Map<String, String> directHheaderParamsMap) {
        StringBuffer sb = new StringBuffer("curl ");
        sb.append(genCurlHeaders(directHheaderParamsMap));
        sb.append(genCurlHeaders(headerParams));
        if (params != null) {
            StringBuffer postSB = new StringBuffer();

            Entry e;
            for(Iterator var7 = params.entrySet().iterator(); var7.hasNext(); postSB.append((String)e.getKey()).append("=").append(URLEncoder.encode((String)e.getValue()))) {
                e = (Entry)var7.next();
                if (postSB.length() > 0) {
                    postSB.append("&");
                }
            }

            if (postSB.length() > 0) {
                sb.append(" -d \"");
                postSB.append("\"");
                sb.append(postSB.toString());
            } else {
                sb.append("--data ''");
            }
        } else {
            sb.append("--data '");
            sb.append(urlEncodedString(toNVP(params), "UTF-8"));
            sb.append("'");
        }

        sb.append(" --insecure ");
        sb.append("\"");
        sb.append(url);
        sb.append("\"");
        return sb.toString();
    }

    private static String urlEncodedString(List<NameValuePair> parameters, String charset) {
        return URLEncodedUtils.format(parameters, charset != null ? charset : HTTP.DEF_CONTENT_CHARSET.name());
    }

    public static HttpPost createPost(String url, Map<String, String> urlParams, Map<String, String> headerParams, ContentBody cb) {
        String newUrl = url;
        if (cb != null && urlParams != null && urlParams != null) {
            List<NameValuePair> nvps = toNVP(urlParams);
            String newParamStr = urlEncodedString(nvps, "UTF-8");
            if (!url.contains("?")) {
                newUrl = String.format("%s?%s", url, newParamStr);
            } else {
                newUrl = String.format("%s&%s", url, newParamStr);
            }
        }

        printDebugInfo("new requestURL=" + newUrl);
        HttpPost httpost = new HttpPost(newUrl);
        setHeaders(httpost, headerParams);
        if (cb == null) {
            List nvps = toNVP(urlParams);

            try {
                httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException var8) {
                var8.printStackTrace();
            }
        } else if (cb.getContentType() == Type.JSON) {
            StringEntity entity = new StringEntity((String)cb.getContentBody(), "UTF-8");
            entity.setContentType(Type.JSON.getContentType());
            httpost.setEntity(entity);
        } else {
            httpost.setHeader("Content-Type", Type.BINARY.getContentType());
            ByteArrayEntity be = new ByteArrayEntity((byte[])((byte[])cb.getContentBody()));
            httpost.setEntity(be);
        }

        return httpost;
    }

    private static List<NameValuePair> toNVP(Map<String, String> urlParams) {
        List<NameValuePair> nvps = new ArrayList();
        if (urlParams != null) {
            Set<String> keySet = urlParams.keySet();
            Iterator var3 = keySet.iterator();

            while(var3.hasNext()) {
                String key = (String)var3.next();
                nvps.add(new BasicNameValuePair(key, (String)urlParams.get(key)));
            }
        }

        return nvps;
    }

    public static void setDirectHeaders(HttpPost httpPost, Map<String, String> directHheaderParamsMap) {
        if (directHheaderParamsMap != null) {
            Iterator var2 = directHheaderParamsMap.entrySet().iterator();

            while(true) {
                Entry kv;
                do {
                    do {
                        if (!var2.hasNext()) {
                            return;
                        }

                        kv = (Entry)var2.next();
                    } while(kv.getKey() == null);
                } while(!"Content-Type".equals(kv.getKey()) && httpPost.containsHeader((String)kv.getKey()));

                httpPost.addHeader((String)kv.getKey(), (String)kv.getValue());
            }
        }
    }

    public static String getUrlPathInfo(String url) throws HttpCallerException {
        URL urlStr = null;

        try {
            urlStr = new URL(url);
        } catch (Exception var3) {
            throw new HttpCallerException("url is unformat, url is " + url);
        }

        String path = urlStr.getPath();
        return path;
    }

    public static String fetchResHeaders(HttpResponse response) {
        if (response != null) {
            StringBuffer body = new StringBuffer();
            body.append(String.format("\"%s\":\"%s\"", "HTTP-STATUS", response.getStatusLine()));
            Header[] var2 = response.getAllHeaders();
            int var3 = var2.length;

            for(int var4 = 0; var4 < var3; ++var4) {
                Header header = var2[var4];
                if (body.length() > 0) {
                    body.append(",");
                }

                body.append(String.format("\"%s\":\"%s\"", header.getName(), header.getValue()));
            }

            return String.format("{%s}", body.toString());
        } else {
            return null;
        }
    }

    public static String generateAsEncodeRequestUrl(String requestURL, Map<String, List<String>> urlParamsMap) {
        requestURL = trimUrl(requestURL);
        StringBuffer params = new StringBuffer();
        Iterator var3 = urlParamsMap.entrySet().iterator();

        while(true) {
            Entry kv;
            do {
                if (!var3.hasNext()) {
                    String newRequestURL = requestURL;
                    if (params.length() > 0) {
                        newRequestURL = requestURL + "?" + params.toString();
                    }

                    printDebugInfo("-- requestURL=" + newRequestURL);
                    return newRequestURL;
                }

                kv = (Entry)var3.next();
                if (params.length() > 0) {
                    params.append("&");
                }
            } while(kv.getValue() == null);

            List<String> vlist = (List)kv.getValue();
            Iterator var6 = vlist.iterator();

            while(var6.hasNext()) {
                String v = (String)var6.next();
                params.append(URLEncoder.encode((String)kv.getKey())).append("=").append(URLEncoder.encode(v));
            }
        }
    }
}
